package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * 购销合同模块
 */
@Controller
@RequestMapping("/cargo/export")
@Slf4j
public class ExportController extends BaseController {

    // 注入dubbo服务接口代理对象（注意导入的包）
    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;

    /**
     * 合同列表
     */
    @RequestMapping("/contractList")
    public String contractList(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行查询合同列表:");

        // 构造条件对象：根据企业id查询、创建时间降序排序
        ContractExample example = new ContractExample();
        // 降序排序
        example.setOrderByClause("create_time desc");
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        // 显示状态位1的购销合同
        criteria.andStateEqualTo(5);

        // 分页查询
        PageInfo<Contract> pageInfo = contractService.findByPage(example, pageNum, pageSize);

        request.setAttribute("pageInfo", pageInfo);
        return "cargo/export/export-contractList";
    }


    /**
     * 报运单列表
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行查询合同列表:");

        // 构造条件对象：根据企业id查询、创建时间降序排序
        ExportExample example = new ExportExample();
        example.setOrderByClause("create_time desc");
        ExportExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getLoginCompanyId());

        // 分页查询
        PageInfo<Export> pageInfo = exportService.findByPage(example, pageNum, pageSize);

        request.setAttribute("pageInfo", pageInfo);
        return "cargo/export/export-list";
    }

    /**
     * 合同管理，点击报运，进入报运单添加页面
     */
    @RequestMapping("/toExport")
    public String toExport(String id) {
        request.setAttribute("id", id);
        return "cargo/export/export-toExport";
    }


    /**
     * 添加或修改
     */
    @RequestMapping("/edit")
    public String edit(Export export) {
        // 设置企业信息（从登陆用户中获取）
        export.setCompanyId(getLoginCompanyId());
        export.setCompanyName(getLoginCompanyName());

        // 判断：根据id是否为空判断执行添加还是修改
        if (StringUtils.isEmpty(export.getId())) {
            export.setCreateTime(new Date());
            // 添加
            exportService.save(export);
        } else {
            // 修改
            exportService.update(export);
        }

        return "redirect:/cargo/export/list";
    }

    @Reference
    private ExportProductService exportProductService;

    /**
     * 进入修改页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id, Model model) {
        // 1. 根据报运单id查询报运单
        Export export = exportService.findById(id);
        model.addAttribute("export", export);

        // 2. 根据报运单id查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> eps = exportProductService.findAll(example);
        model.addAttribute("eps", eps);
        return "cargo/export/export-update";
    }

    @RequestMapping("/submit")
    public String submit(String id) {
        // 提交：修改购销合同状态改为1
        Export export = new Export();
        // 设置修改条件
        export.setId(id);
        // 设置修改的状态值
        export.setState(1);
        // 修改 (动态sql，有选择的修改)
        exportService.update(export);
        return "redirect:/cargo/export/list";
    }

    /**
     * 检查点击取消按钮时报运单的状态
     */
    @RequestMapping("/checkExportCancel")
    @ResponseBody
    public Integer checkExportCancel(String id){
        Export export = exportService.findById(id);
        Integer state = export.getState();
        if(state ==0){
            return 0;
        } else if(state==4){
            return 4;
        }
        return 1;
    }

    @RequestMapping("/cancel")
    public String cancel(String id) {
        // 取消：修改购销合同状态改为0
        Export export = new Export();
        // 设置修改条件
        export.setId(id);
        // 设置修改的状态值
        export.setState(0);
        // 修改 (动态sql，有选择的修改)
        exportService.update(export);
        return "redirect:/cargo/export/list";
    }


    /**
     * 电子报运
     */
    @RequestMapping("/exportE")
    public String exportE(String id) {

        //1、创建webservice请求需要的对象
        ExportVo exportVo = new ExportVo();
        //1.1 根据报运单id查询
        Export export = exportService.findById(id);
        //1.2 对象拷贝 [参数1：数据源； 参数2：目标对象]
        BeanUtils.copyProperties(export,exportVo);
        //1.3 设置报运单id
        exportVo.setExportId(id);

        //1.4 封装商品信息
        List<ExportProductVo> products = exportVo.getProducts();
        //1.4.1 根据报运单id查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(example);
        //1.4.2 遍历查询的商品，添加到products集合
        if (list != null && list.size() > 0) {
            for (ExportProduct exportProduct : list) {
                // 创建webservice请求封装商品的对象
                ExportProductVo vo = new ExportProductVo();
                // 拷贝
                BeanUtils.copyProperties(exportProduct,vo);
                // 设置报运单、商品id
                vo.setExportId(id);
                vo.setExportProductId(exportProduct.getId());
                // 添加到集合
                products.add(vo);
            }
        }
        //exportVo.setProducts(products);


        //2、远程调用（1）保存报运单信息到海关报运平台的数据库中
        WebClient.create("http://localhost:8088/ws/export/user").post(exportVo);
        //3、远程调用（2）查询报运结果
        ExportResult exportResult =
                WebClient
                        .create("http://localhost:8088/ws/export/user/" + id)
                        .get(ExportResult.class);

        //4、修改报运单
        exportService.updateExport(exportResult);
        return "redirect:/cargo/export/list";
    }

    /**
     * 检查报运单的state
     * @return
     */
    @RequestMapping("/checkExportState")
    @ResponseBody
    public Integer checkExportState(String id){
        Export export = exportService.findById(id);
        Integer state = export.getState();
        if(state ==1){
            return 1;
        }
        else if(state==2){
            return 2;
        }else if(state==4){
            return 4;
        }
        return 0;
    }

    /**
     * 检查提交按钮export的状态
     */
    @RequestMapping("/checkExportSubmit")
    @ResponseBody
    public Integer checkExportSubmit(String id){
        Export export = exportService.findById(id);
        Integer state = export.getState();
         if(state==1){
            return 1;
        }else if(state==2){
             return 2;
         }else if(state==4){
             return 4;
         }
        return 0;
    }

    /**
     * 删除报运单
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Integer delete(String id){
        Export export = exportService.findById(id);
        if (export.getState()==0){
            exportService.delete(id);
            return 0;
        }
        return 1;
    }

    /**
     * 查看报运单
     */
    @RequestMapping("/toView")
    public String toView(String id){
        // 1. 根据报运单id查询报运单
        Export export = exportService.findById(id);
        request.setAttribute("export", export);

        // 2. 根据报运单id查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> eps = exportProductService.findAll(example);
        request.setAttribute("eps", eps);
        return "cargo/export/export-view";
    }

}















